/*
 * MIT License
 *
 * Copyright (c) 2023-present, tangli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package tony.core.jackson

/**
 * Jackson 反序列化注入
 * @author tangli
 * @date 2023/09/28 19:16
 */
import com.fasterxml.jackson.databind.JsonNode
import java.util.function.Supplier
import org.slf4j.LoggerFactory
import tony.core.utils.throwIfNull

/**
 * jackson 序列化 注入器工厂
 * @author tangli
 * @date 2025/10/31 12:56
 */
public open class SerializeInjectorFactory {
    protected val serializeInjectorSupplierMap: MutableMap<String, SerializeInjectorSupplier<*>> = mutableMapOf()
    private val logger = LoggerFactory.getLogger(javaClass)

    public fun register(
        name: String,
        serializeInjectorSupplier: SerializeInjectorSupplier<*>,
    ) {
        if (serializeInjectorSupplierMap.contains(name)) {
            logger.warn("Serialize Injector Supplier for name $name will be overridden.")
        }
        serializeInjectorSupplierMap[name] = serializeInjectorSupplier
    }

    public fun getSerializeInjector(name: String): SerializeInjector =
        serializeInjectorSupplierMap[name]
            .throwIfNull("$name serializeInjectorSupplier not found")
            .get()
}

/**
 * jackson 序列化 注入器 supplier
 *
 * @author tangli
 * @date 2025/10/31 12:56
 */
public interface SerializeInjectorSupplier<T : SerializeInjector> : Supplier<T> {
    public val name: String

    override fun get(): T
}

/**
 * jackson 序列化 注入器
 * @author tangli
 * @date 2025/10/31 12:56
 */
public interface SerializeInjector {
    public var params: MutableList<String>
    public var targetFieldName: String

    public fun inject(source: JsonNode): Any
}
